package com.windward.vii.service;

import com.windward.vii.common.JsonResult;
import com.windward.vii.common.RedisConstants;
import com.windward.vii.dao.entity.User;
import com.windward.vii.dao.entity.UserToken;
import com.windward.vii.dao.mapper.UserMapper;
import com.windward.vii.dao.mapper.UserTokenMapper;
import com.windward.vii.framework.RedisManager;
import com.windward.vii.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class UserTokenService {

    @Resource
    UserTokenMapper userTokenMapper;
    @Resource
    RedisManager redisManager;
    @Resource
    UserMapper userMapper;

    /**
     * 新增一条记录
     * @param userToken
     * @return
     */
    public boolean insert(UserToken userToken) {
        int res = userTokenMapper.insertSelective(userToken);
        if (res > 0) {
            redisManager.set(RedisConstants.TOKEN + userToken.getToken(),
                    String.valueOf(userToken.getUid()), userToken.getExpireTime());
        }
        return res > 0;
    }

    public boolean deleteTokenByUid(Long uid) {
        List<UserToken> userTokenList = userTokenMapper.getTokenByUid(uid);
        if(userTokenList != null && userTokenList.size() > 0) {
            try {
                for(UserToken userToken : userTokenList) {
                    userTokenMapper.deleteByPrimaryKey(userToken.getId());
                    redisManager.del(RedisConstants.TOKEN + userToken.getToken());
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * 把当前Token置为失效
     * @param token
     * @return
     */
    public JsonResult logoutByToken(String token) {
        // 把当前user的deviceToken置空，防止无效push
        UserToken userToken = userTokenMapper.getByToken(token);
        if(userToken != null) {
            User updateRecord = new User();
            updateRecord.setId(userToken.getUid());
            updateRecord.setDeviceToken("");
            userMapper.updateByPrimaryKeySelective(updateRecord);
        }
        userTokenMapper.deleteByToken(token);
        redisManager.del(RedisConstants.TOKEN + token);
        return JsonResult.success();
    }

    /**
     * 根据token得到uid，过期
     * @param token
     * @return 不存在，过期，返回0
     *         存在，不过期，返回uid
     */
    public long getUidByToken(String token) {
        Long uid = 0l;
        if(redisManager.isConnected()) {
            String cacheUid = redisManager.get(RedisConstants.TOKEN + token);
            if(!StringUtils.isBlank(cacheUid)) {
                uid = Long.valueOf(cacheUid);
            }
        }
        if(uid < 1) {
            UserToken userToken = userTokenMapper.getByToken(token);
            if(userToken != null) {
                uid = userToken.getUid();
                try {
                    redisManager.set(RedisConstants.TOKEN + userToken.getToken(),
                            String.valueOf(userToken.getUid()), userToken.getExpireTime());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return uid;
    }

    /**
     * 根据uid、终端类型删除(禁止多浏览器登陆时使用)
     * @param uid
     * @param terminalType
     * @return
     */
    public int deleteByUidAndTerminalType(Long uid, Integer terminalType) {
        Map<String, Object> map = new HashMap<>();
        map.put("uid", uid);
        map.put("terminalType", terminalType);
        return userTokenMapper.deleteByUidAndTerminalType(map);
    }

}
